<?php
namespace Cyfy\Modules\FlickrCustomSetGallery;
use \Cyfy\Modules\phpFlickr\phpFlickr;

class Module extends \Cyfy\Module
{
    const API = "505dddc3c52221f762786f1a74799df9";
    const SECRET = "edbf798c7d77bb9b";
    const SETS_ON_PAGE = 10;
    const PATH = "galerie/fotogalerie";
    const ID_POSITION = 2;
    
    static $cache = false;
    static $pager = "";

    static function ajax($name)
    {
        switch($name)
        {
            case "saveSets":
                return self :: ajaxSaveSets();
            case "deleteSets":
                return self :: ajaxDeleteSets();
            case "getSets":
                return self :: ajaxGetSets();
        }
    }
    
    static function administration($name = "")
	{
		switch($name){
            case "settings":
                $form = new Forms\Settings();
                $form -> SetDataFromConstants(array("setsOnPage", "path", "id"));
                return $form -> show();
                
            default:
       			return array(
                    "settings" => array("name" => self :: t(10), "description" => self :: t(20), "permission"=> "administration")
                );
        }
	}
    
    
    static function get($what)
    {
        \Cyfy\Cyfy ::  CSS(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/FlickrCustomSetGallery/flickrGallery.css"), "file");

        
        switch($what){
            case "main":
                return self :: main();
            case "set":
                return self :: set(\Cyfy\Cyfy ::  arg(self :: ID_POSITION));
        }
    }
    
 
    static private function main()
    {
        \Cyfy\Template :: setTitle(self :: t(110));
        
        $output = "<h2>" . self :: t(110) . "</h2>\n"; 
        $output .= "<div id=\"flickrGallery\">\n";

        $output .= self :: ajaxGetSets();

        $output .= "</div>\n\n";
        return $output;
    }

    static private function ajaxGetSets(){
        
		// start and end
		if($_REQUEST["start"]){
            $start = $_REQUEST["start"];
        }else{
            $start = 0;
        }
        
        // per page
        $perPage = (self :: constant("setsOnPage")) ? self :: constant("setsOnPage") : self :: SETS_ON_PAGE;
		
		// number of all sets
        $result = \dibi :: query("SELECT [sid] FROM [:cyfy:FlickrCustomSetGallery-sets]");
		$numberOfSets = count($result);
		
		$allSetsInDb = array();
		foreach($result as $ids){
            $allSetsInDb[] = $ids['sid'];
        }
		
		// flickr connection
		
        $f = new phpFlickr(self::API, self :: SECRET);
        
        if(self :: $cache) $f->enableCache("db", "mysql://" . \Cyfy\Cyfy ::  $dbUsername . ":". \Cyfy\Cyfy ::  $dbPassword ."@".\Cyfy\Cyfy ::  $dbHost ."/". \Cyfy\Cyfy ::  $dbDatabase."");
        
        
        $sets = array_shift($f->photosets_getList(self :: constant("id")));
        
        // pager
       // $output .= self :: getPager($numberOfSets, $start);
        
		$perm = \Cyfy\Cyfy ::  permission("FlickrCustomSetGallery", "administration");
		// only values start to end
        $skipped = 0;
		$count = 0;
		$toShow = array();
		$addedIds = array();
		foreach($sets as $set){
			if(in_array($set["id"], $allSetsInDb)){
				$addedIds[] = $set["id"];
				if($skipped < $start){
					$skipped++;
				}else{
					if ($count < $perPage){
						$toShow[] = $set;			
						$count++;
					}else{
						if($perm == false){
							break;
						}
					}
				}
			}		
		}

		// form        
        if($perm){
            $output .= self :: showOnlyForm($addedIds);
        }
        
		// print values
        foreach($toShow as $set)
        {
            $url = \Cyfy\Cyfy ::  getPath(self :: PATH . "/".$set["id"]);
        
			$output .= "<div class=\"flickrGallerySet\">\n";
			$output .= "    <a href=\"" . $url . "\" title=\"".$set["title"]."\"><img class=\"flickrGalleryImage\" alt=\"".$set["title"]."\" src=\"http://static.flickr.com/{$set["server"]}/{$set["primary"]}_{$set["secret"]}_s.jpg\" /></a>\n";
			$output .= "    <div class=\"info\"><h3><a href=\"". $url . "\">{$set["title"]}</a></h3>\n";
			$output .= "    <p>{$set["description"]}</p>\n";
			
			if($perm)
            {
				$output .= "    <p><a href=\"#\" onclick=\"Cyfy.ajax('FlickrCustomSetGallery', 'deleteSets', '#flickrGallery', 'set={$set["id"]}'); return false;\">". self :: t (120) ."</a></p>\n";
			}
			$output .= "</div></div>\n\n";
        }
        
        $output .= self :: getPager($numberOfSets, $start);
        
        return $output;
    }
    
    static private function getPager($count, $start)
    {
        if(self :: $pager != ""){
            return self :: $pager;
        }
        
        $pages = array();  
		$perPage = (self :: constant("setsOnPage")) ? self :: constant("setsOnPage") : self :: SETS_ON_PAGE;
		$div = $count / $perPage;
		
        for($i=0; $i < $div;$i++){
            $link = $i * $perPage;
            $active = ($start == $link) ? true : false;
            $pages[] = array("number"=>$i + 1, "active"=>$active, "link" => $link);
        }

        $output = "<ul class=\"pager\">\n";
        foreach($pages as $p){
            // Is this page active?
            if($p["active"]){
                $li = " class=\"active\"";
            }else{
                $li = "";   
            }
            $output .= "  <li{$li}><a href=\"?start={$p["link"]}\" onclick=\"Cyfy.ajax('FlickrCustomSetGallery', 'getSets', '#flickrGallery', 'start={$p["link"]}'); Cyfy.redirectToOutside('#photgallery-".$p["link"]."'); return false;\">{$p["number"]}</a></li>\n";
        }
        $output .= "</ul>\n";
        $output .= "<div class=\"pagerClear\"></div>\n";
        self :: $pager = $output;
        return $output;
    }
    
    static private function showOnlyForm($shown)
    {
        $f = new phpFlickr(self::API, self :: SECRET);
        if(self :: $cache) $f->enableCache("db", "mysql://" . \Cyfy\Cyfy ::  $dbUsername . ":". \Cyfy\Cyfy ::  $dbPassword ."@".\Cyfy\Cyfy ::  $dbHost ."/". \Cyfy\Cyfy ::  $dbDatabase."");
        $sets = array_pop($f->photosets_getList(self :: Constant("id")));
        
        $output = "<h3>" . self :: t(130) . "</h3>\n";
        $output .= "<form class=\"forms_addSetForm\">\n";
        $output .= "    <select onchange=\"if($(this).val()){ Cyfy.ajax('FlickrCustomSetGallery', 'saveSets', '#flickrGallery', 'set='+$(this).val()); this.selectedIndex=0}\" name=\"set\" class=\"chooseSet\">\n";
        $output .= "        <option value=\"\">" . self::t(140) . "</option>\n";
        
        foreach ($sets as $set)
        {
            if(in_array($set["id"], $shown) == false){
                $output .= "        <option value=\"{$set["id"]}\">{$set["title"]}</option>\n";
            }
        }
        
        $output .= "    </select>\n";
        $output .= "    </form>\n";
        return $output;
    }
    
    static private function set($id){
        
        $f = new phpFlickr(self::API, self :: SECRET);
        if(self :: $cache) $f->enableCache("db", "mysql://" . \Cyfy\Cyfy ::  $dbUsername . ":". \Cyfy\Cyfy ::  $dbPassword ."@".\Cyfy\Cyfy ::  $dbHost ."/". \Cyfy\Cyfy ::  $dbDatabase."");
        
        $resource = $f->photosets_getPhotos($id);
        $photoset = $f->photosets_getInfo($id);
      
        // not found
        if($photoset == false)
        {
            \Cyfy\Message :: set(self :: t(211, array($id)), \Cyfy\Message::ERROR);
            return false;
        }
        
        \Cyfy\Template :: setTitle($photoset["title"]);
        
        $output = "<h2>" . $photoset["title"] . "</h2>\n";
        $output .= "<p>" . $photoset["description"] . "</p>\n";
        $output .= "<div class=\"flickrGalleryPhotos\">\n";
        
        // list photos
        foreach($resource["photoset"]["photo"] as $photo)
        {
            $output .= "    <a href=\"".$f -> buildPhotoURL($photo,"larger")."\" title=\"".$photo["title"]."\" rel=\"lightbox-flickr\"><img class=\"flickrGalleryImage\" alt=\"".$photo["title"]."\" src=\"".$f -> buildPhotoURL($photo,"square")."\" /></a>\n";
        }        
        
        $output .= "</div>\n";
        
        return $output;
    }
    
    static private function ajaxSaveSets()
    {
        if(\Cyfy\Cyfy ::  permission("FlickrCustomSetGallery","add and remove sets"))
        {
            \dibi :: query("INSERT INTO [:cyfy:FlickrCustomSetGallery-sets] VALUES(%s)", $_POST["set"]);
            \Cyfy\Message :: set(self :: t(150));
            
            return self :: ajaxGetSets();
        }
    }
    
    static private function ajaxDeleteSets()
    {
        if(\Cyfy\Cyfy ::  permission("FlickrCustomSetGallery","add and remove sets"))
        {
            \dibi :: query("DELETE FROM [:cyfy:FlickrCustomSetGallery-sets] WHERE sid = %s", $_POST["set"]);
            \Cyfy\Message :: set(self :: t(160));
            
            return self :: ajaxGetSets();
        }
    }
}
